package com.xinggq.common.interceptor;

import com.xinggq.common.context.TraceContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 链路追踪拦截器
 * 在请求开始时生成或获取追踪ID并设置到ThreadLocal中
 * 在响应头中返回追踪ID，在请求结束时清理ThreadLocal
 *
 * @author system
 * @since 2025/1/10
 */
@Slf4j
@Component
@Order(0)
public class TraceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 优先从请求头获取追踪ID
        String traceId = request.getHeader(TraceContext.TRACE_ID_HEADER);
        
        // 如果请求头中没有追踪ID，则生成新的
        if (traceId == null || traceId.trim().isEmpty()) {
            traceId = TraceContext.generateTraceId();
            log.debug("生成新的追踪ID: {}", traceId);
        } else {
            log.debug("从请求头获取追踪ID: {}", traceId);
        }
        
        // 设置到ThreadLocal中
        TraceContext.setTraceId(traceId);
        
        // 设置到MDC中，供logback使用
        MDC.put("traceId", traceId);
        
        // 在响应头中返回追踪ID
        response.setHeader(TraceContext.TRACE_ID_HEADER, traceId);
        
        log.debug("请求开始 - URI: {}, Method: {}, TraceId: {}", 
                 request.getRequestURI(), request.getMethod(), traceId);
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                               Object handler, Exception ex) {
        String traceId = TraceContext.getTraceId();
        
        log.debug("请求结束 - URI: {}, Method: {}, TraceId: {}, Status: {}", 
                 request.getRequestURI(), request.getMethod(), traceId, response.getStatus());
        
        // 清理ThreadLocal和MDC，避免内存泄漏
        TraceContext.clear();
        MDC.remove("traceId");
        log.debug("清理ThreadLocal和MDC中的追踪ID: {}", traceId);
    }
}